package com.atom.module.mvvm.extren

import android.widget.AbsListView
import androidx.annotation.CheckResult
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate

@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
fun AbsListView.scrollEvents() = callbackFlow<ScrollEvent> {
    checkMainThread()
    val listener = object : AbsListView.OnScrollListener {

        private var currentScrollState = AbsListView.OnScrollListener.SCROLL_STATE_IDLE

        override fun onScrollStateChanged(absListView: AbsListView, scrollState: Int) {
            currentScrollState = scrollState
            trySend(
                ScrollEvent(
                    view = this@scrollEvents,
                    scrollState = scrollState,
                    firstVisibleItem = firstVisiblePosition,
                    visibleItemCount = childCount,
                    totalItemCount = count
                )
            )
        }

        override fun onScroll(
            absListView: AbsListView,
            firstVisibleItem: Int,
            visibleItemCount: Int,
            totalItemCount: Int
        ) {
            trySend(
                ScrollEvent(
                    view = this@scrollEvents,
                    scrollState = currentScrollState,
                    firstVisibleItem = firstVisibleItem,
                    visibleItemCount = visibleItemCount,
                    totalItemCount = totalItemCount
                )
            )
        }
    }
    setOnScrollListener(listener)
    awaitClose { setOnScrollListener(null) }
}.conflate()
